<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      /**
       * Definition for a binary tree node.
       * function TreeNodes(val, left, right) {
       *     this.val = (val===undefined ? 0 : val)
       *     this.left = (left===undefined ? null : left)
       *     this.right = (right===undefined ? null : right)
       * }
       */
      /**
       * @param {TreeNodes} root
       * @return {number}
       */

      class TreeNodes {
        constructor(val) {
          this.val = val
          this.left = this.right = null
        }
      }

      var getMinimumDifference = function (root) {
        let minDiff = Infinity
        let prevVal = null
        console.log('root', root)
        // 中序遍历二叉搜索树
        const inorderTraversal = function (node) {
          if (node === null) {
            return
          }

          // 遍历左子树
          inorderTraversal(node.left)

          // 计算当前节点值与前一个节点值的差值
          if (prevVal !== null) {
            minDiff = Math.min(minDiff, node.val - prevVal)
            console.log('minDiff', minDiff)
          }

          // 更新前一个节点值
          prevVal = node.val
          console.log('prevVal', node.left, prevVal)

          // 遍历右子树
          inorderTraversal(node.right)
        }

        // 开始中序遍历
        inorderTraversal(root)

        return minDiff
      }

      // 示例
      const root = new TreeNodes(1)
      root.left = new TreeNodes(0)
      root.right = new TreeNodes(48)
      root.right.left = new TreeNodes(12)
      root.right.right = new TreeNodes(49)

      const result = getMinimumDifference(root)
      console.log(result) // 输出最小差值
    </script>
  </body>
</html>
